package com.app.core.util;

import java.security.InvalidParameterException;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class AESUtil {
	public static final String AES_KEY = "20160701djwe1000";
	public static final byte[] IV_STR_BYTE = "20160701djwe2000".getBytes();
	public static final String CODE = "UTF-8";

	public static String encrypt(String src) throws Exception {
		return encrypt(src, AES_KEY);
	}

	public static String decrypt(String src) throws Exception {
		return decrypt(src, AES_KEY);
	}

	// 加密
	public static String encrypt(String src, String key) throws Exception {
		if (key == null) {
			throw new NullPointerException("key不能为空");
		}
		// 判断Key是否为16位
		if (key.length() != 16) {
			throw new InvalidParameterException("Key长度不是16位");
		}
		byte[] raw = key.getBytes();
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		// "算法/模式/补码方式"
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
		IvParameterSpec iv = new IvParameterSpec(IV_STR_BYTE);
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
		byte[] encrypted = cipher.doFinal(src.getBytes());
		// 此处使用BASE64做转码功能，同时能起到2次加密的作用。
		return Base64.encodeBase64String(encrypted);
	}

	// 解密
	public static String decrypt(String src, String key) throws Exception {
		if (key == null) {
			throw new NullPointerException("key不能为空");
		}
		// 判断Key是否为16位
		if (key.length() != 16) {
			throw new InvalidParameterException("Key长度不是16位");
		}

		byte[] raw = key.getBytes(CODE);
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		IvParameterSpec iv = new IvParameterSpec(IV_STR_BYTE);
		cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
		// 先用base64解密
		byte[] encrypted1 = Base64.decodeBase64(src);
		byte[] original = cipher.doFinal(encrypted1);
		String originalString = new String(original);

		return originalString;
	}

	public static void main(String[] args) throws Exception {
		// 需要加密的字串
		String cSrc = "412728199101011210";
		System.out.println(cSrc);

		// 加密
		long lStart = System.currentTimeMillis();
		String enString = AESUtil.encrypt(cSrc);
		System.out.println("加密后的字串是：" + enString);

		long lUseTime = System.currentTimeMillis() - lStart;
		System.out.println("加密耗时：" + lUseTime + "毫秒");

		// 解密
		lStart = System.currentTimeMillis();
		String DeString = AESUtil.decrypt("sVAs67FkOrVmevm9hNblbH2Cd37fLey1gOH98i+oQ80=");
		System.out.println("解密后的字串是：" + DeString);
		lUseTime = System.currentTimeMillis() - lStart;
		System.out.println("解密耗时：" + lUseTime + "毫秒");
	}
}
